import { getCourseWords, completeCourse } from '@/api/readings';

/**
 * 导航功能模块
 */
export const useNavigation = (route, router, sessionProgress, wordData) => {
  /**
   * 处理返回按钮点击
   */
  const handleBack = async () => {
    try {
      if (sessionProgress.needsSaving) {
        await getCourseWords(route.params.id);
        sessionProgress.needsSaving = false;
      }
      window.history.back();
    } catch (error) {
      console.error('返回时出错:', error);
      router.push('/home/reading');
    }
  };
  
  /**
   * 生成AI文章并跳转
   */
  const generateEssay = async () => {
    try {
      // 保存进度
      if (sessionProgress.needsSaving) {
        await getCourseWords(route.params.id);
        sessionProgress.needsSaving = false;
      }
      
      // 尝试标记课程为已完成
      // try {
      //   await completeCourse(route.params.id);
      // } catch (error) {
      //   console.error('完成课程失败:', error);
      // }
      
      // 获取文章ID并跳转
      const response = await getCourseWords(route.params.id);
      if (response.code == 0 && response.data) {
        router.push(`/reading/essay/${response.data.article_id}`);
      }
    } catch (error) {
      console.error('跳转文章失败:', error);
    }
  };

  return {
    handleBack,
    generateEssay
  };
}; 